package com.hliushi.mq.delay;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.concurrent.TimeUnit;

/**
 * 发送同步消息
 *
 * @author llhuang10
 * @date 2021/8/11 16:04
 */
public class DelaySyncProducer {


    public static void main(String[] args) {
        // 1.创建消息生产者producer, 并指定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("group1");
        // 2.指定Nameserver地址
        producer.setNamesrvAddr("cvm-node01:9876;cvm-node02:9876");
        // 3.发送消息
        try {
            producer.start();
            for (int i = 0; i < 10; i++) {
                // 4.创建消息, 指定主题Topic, Tag和消费题
                Message message = new Message("base", "DelayTag", ("hello world" + i).getBytes());

                // 设置延迟时间
                message.setDelayTimeLevel(2);

                // 5.发送消息
                SendResult result = producer.send(message);
                SendStatus status = result.getSendStatus();
                String msgId = result.getMsgId();
                int queueId = result.getMessageQueue().getQueueId();

                System.out.printf("发送状态:%s, 消息Id=%s, 队列=%s\n", result, msgId, queueId);

                // 线程睡一秒
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (MQClientException | InterruptedException | RemotingException | MQBrokerException e) {
            e.printStackTrace();
        } finally {
            // 6.关闭生产者producer
            System.out.println("发送成功!");
            producer.shutdown();
        }
    }
}
